package com.apache.rpc.dao;

import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.datasource.DynamicDataSource;
import com.apache.database.datasource.DynamicDataSourceHolder;
import com.apache.database.db.DaoImpl;
import com.apache.database.model.MethodParam;
import com.apache.rpc.entity.InterfaceRegister;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository("interfaceRegisterDao")
public class InterfaceRegisterDaoImpl extends DaoImpl {

    protected Logger log = Logger.getLogger(getClass());

    public String getSql(int type) {
        String sql = "";
        switch (type) {
        case 1:
            sql = "select count(*) from InterfaceRegister where 1=1 ";
            break;
        case 2:
            sql = " from InterfaceRegister where 1=1 ";
            break;
        default:
            sql = "select count(*) from InterfaceRegister where 1=1 ";
        }
        return sql;
    }

    public void initSystemCache() {
        MethodParam param = new MethodParam("ByProperty", "", getSql(2),
                "com.apache.rpc.entity.InterfaceRegister");
        param.setParams("flag", "1");
        if(DynamicDataSource.getInstance().getEnableIncludeRpc()){
            String key = DynamicDataSource.getInstance().getRpcDb().getSysEname();
            param.setParams("datasource",key);
            DynamicDataSourceHolder.putDataSource(key);
        }
        List list = this.select(param);
        if (!Validator.isEmpty(list)) {
            int count = list.size();
            log.info("接口注册信息加载start");
            for (int i = 0; i < count; i++) {
                InterfaceRegister register = (InterfaceRegister) list.get(i);
                String key = "interfaceRegister_" + register.getBeanId();
                List<InterfaceRegister> vos = (List) SystemTools.getInstance().getCache("")
                        .getCacheObjectByKey(key);
                if (Validator.isEmpty(vos)) {
                    vos = new ArrayList<InterfaceRegister>();
                } else {
                    for (InterfaceRegister ifr : vos) {
                        if (ifr.getRegisterId().equals(register.getRegisterId())) {
                            vos.remove(ifr);
                            break;
                        }
                    }
                }
                log.info((i+1)+"）接口注册【"+key+"】->"+ JSONObject.fromObject(register).toString());
                vos.add(register);
                SystemTools.getInstance().getCache("").createCacheObject(key, vos);
            }
            log.info("初始化[接口注册信息]["+count+"]条到缓存完成！");
        }
    }
}
